package com.xbongbong.crm.perform.query.render.edit;

import com.alibaba.fastjson.JSONObject;
import com.xbongbong.crm.abstracts.AbstractCrmEditPageRenderService;
import com.xbongbong.crm.help.WorkReportHelp;
import com.xbongbong.paas.constant.MessageConstant;
import com.xbongbong.paas.data.service.RichTextService;
import com.xbongbong.paas.domain.entity.ext.PaasFormDataEntityExt;
import com.xbongbong.paas.domain.entity.ext.PaasFormEntityExt;
import com.xbongbong.paas.enums.DelEnum;
import com.xbongbong.paas.enums.FieldTypeEnum;
import com.xbongbong.paas.enums.FlowStatusEnum;
import com.xbongbong.paas.field.DefaultAttrPoJo;
import com.xbongbong.paas.field.FieldAttrEntity;
import com.xbongbong.paas.help.FormDataHelp;
import com.xbongbong.paas.model.PaasFormModel;
import com.xbongbong.paas.pojo.dto.FormDataUpdateGetDTO;
import com.xbongbong.paas.pojo.vo.ParseSingleRowDataVO;
import com.xbongbong.paas.toolbox.exception.XbbException;
import com.xbongbong.paas.toolbox.util.BeanUtil;
import com.xbongbong.paas.util.ExplainUtil;
import com.xbongbong.pro.businessdata.pojo.dto.FormatExplainDTO;
import com.xbongbong.pro.enums.errorcodes.BuinessDefaultErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.SystemErrorCodeEnum;
import com.xbongbong.pro.enums.errorcodes.WorkReportErrorCodeEnum;
import com.xbongbong.pro.formdata.pojo.dto.SaasAnalysisDataDTO;
import com.xbongbong.pro.formexplain.pojo.vo.HandlerExplainVO;
import com.xbongbong.saas.constant.BasicConstant;
import com.xbongbong.saas.enums.XbbRefTypeEnum;
import com.xbongbong.saas.enums.business.WorkReportFieldEnum;
import com.xbongbong.saas.model.WorkReportModel;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.Collections;
import java.util.List;
import java.util.Map;
import java.util.Objects;

/**
 * @author sunshaoxiang
 * @ClassName WorkReportEditPageRenderServiceImpl
 * @Description 工作报告 update get 业务层
 * @Date 2022/6/9 9:25
 * @Version 1.0
 **/
@Service("workReportEditPageRenderServiceImpl")
public class WorkReportEditPageRenderServiceImpl extends AbstractCrmEditPageRenderService {

    public static final Logger LOGGER = LoggerFactory.getLogger(WorkReportEditPageRenderServiceImpl.class);

    @Resource
    private WorkReportHelp workReportHelp;
    @Resource
    private WorkReportModel workReportModel;
    @Resource
    private PaasFormModel paasFormModel;
    @Resource
    private RichTextService richTextService;
    @Resource
    private FormDataHelp formDataHelp;

    @Override
    public List<Integer> businessType() {
        return Collections.singletonList(XbbRefTypeEnum.WORK_REPORT.getCode());
    }


    @Override
    public PaasFormEntityExt getForm(FormDataUpdateGetDTO formDataUpdateGetDTO) throws XbbException {
//        PaasFormEntityExt paasFormEntityExt = super.getForm(formDataUpdateGetDTO);
        PaasFormEntityExt paasFormEntityExt = paasFormModel.getByBusinessType(formDataUpdateGetDTO.getSubBusinessType(), formDataUpdateGetDTO.getCorpid());
        // fix: 20682 【成功部】移动端周报统计数据没出来，电脑上正常
        if ( paasFormEntityExt == null ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_NOT_EXIST);
        }
        if ( Objects.equals(paasFormEntityExt.getEnable(), 0) || Objects.equals(paasFormEntityExt.getDel(), 1) ) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100017);
        }
        formDataUpdateGetDTO.setSubBusinessType(paasFormEntityExt.getBusinessType());
        formDataUpdateGetDTO.setFormId(paasFormEntityExt.getId());
        return paasFormEntityExt;
    }

    @Override
    public PaasFormDataEntityExt getData(FormDataUpdateGetDTO formDataUpdateGetDTO) throws XbbException {
        //Copy自抽象类,改了一下查富文本businessType
        String corpid = formDataUpdateGetDTO.getCorpid();
        Integer saasMark = formDataUpdateGetDTO.getSaasMark();
        Integer businessType = formDataUpdateGetDTO.getBusinessType();
        Integer subBusinessType = formDataUpdateGetDTO.getSubBusinessType();
        Long dataId = formDataUpdateGetDTO.getDataId();
        PaasFormDataEntityExt paasFormDataEntityExt = formDataHelp.getFormDataEntityExt( corpid, saasMark, businessType, dataId);
        richTextService.addRichTextByDataId(dataId, corpid, formDataUpdateGetDTO.getFormId(), subBusinessType, saasMark, paasFormDataEntityExt.getDel(), paasFormDataEntityExt.getData());
        if (paasFormDataEntityExt == null) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100001, MessageConstant.FORM_DATA_NOT_EXIST);
        }
        if (Objects.equals(paasFormDataEntityExt.getDel(), DelEnum.DELETE.getDel())) {
            throw new XbbException(SystemErrorCodeEnum.API_ERROR_100404);

        }
        if (FlowStatusEnum.inApproval(paasFormDataEntityExt.getFlowStatus()) && !Objects.equals(businessType, XbbRefTypeEnum.DISTRIBUTOR_ACCOUNT.getCode())) {
            throw new XbbException(BuinessDefaultErrorCodeEnum.API_ERROR_200020);
        }
        return paasFormDataEntityExt;
    }

    @Override
    public ParseSingleRowDataVO formatData(FormDataUpdateGetDTO formDataUpdateGetDTO, HandlerExplainVO handlerExplainVO, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        if (!Objects.equals(formDataUpdateGetDTO.getUserId(), paasFormDataEntityExt.getCreatorId())) {
            // 自己只能编辑自己的工作报告
            throw new XbbException(WorkReportErrorCodeEnum.API_ERROR_207024);
        }

        SaasAnalysisDataDTO saasAnalysisDataDTO = new SaasAnalysisDataDTO();
        BeanUtil.copyProperties(formDataUpdateGetDTO, saasAnalysisDataDTO);
        // saas特殊格式转换
        Map<String, FieldAttrEntity> explainMap = ExplainUtil.getExplainMapByList(handlerExplainVO.getHeadList());
        JSONObject data = paasFormDataEntityExt.getData();
        saasAnalysisDataDTO.setExplainMap(explainMap);
        workReportModel.formatData(saasAnalysisDataDTO, data);

        // 工作报告的统计数据，需要从解释里取
        if (Objects.nonNull(getStatisticData(handlerExplainVO.getHeadList()))) {
            data.put(WorkReportFieldEnum.THIS_STATISTIC.getAttr(), getStatisticData(handlerExplainVO.getHeadList()));
        }

        data.put(FieldTypeEnum.OWNERID.getAlias(), handlerExplainVO.getOwnerId());
        data.put(FieldTypeEnum.COUSERID.getAlias(), handlerExplainVO.getCoUserId());
        data.put(FieldTypeEnum.DEPARTMENTID.getAlias(), paasFormDataEntityExt.getDepartmentId());
        data.put(FieldTypeEnum.SERIALNO.getAlias(), paasFormDataEntityExt.getSerialNo());
        ParseSingleRowDataVO parseSingleRowDataVO = parseSingleRowData(formDataUpdateGetDTO, data, explainMap, handlerExplainVO.getUserMap(), handlerExplainVO.getDepartmentMap());
        paasFormDataEntityExt.setData(parseSingleRowDataVO.getResult());
        return parseSingleRowDataVO;
    }

    /**
     * 工作报告的统计数据，需要从解释里取
     * @param explainList
     * @return
     */
    private Object getStatisticData(List<FieldAttrEntity> explainList) {
        Map<String, FieldAttrEntity> statisticsMap = ExplainUtil.getExplainMapByList(explainList, WorkReportFieldEnum.THIS_STATISTIC.getAttr());
        FieldAttrEntity attrEntity = statisticsMap.get(WorkReportFieldEnum.THIS_STATISTIC.getAttr());
        if (Objects.nonNull(attrEntity)) {
            DefaultAttrPoJo statisticsPojo = attrEntity.getDefaultAttr();
            return statisticsPojo.getDefaultValue();
        }
        return null;
    }

    @Override
    public void businessHandleExplain(FormDataUpdateGetDTO formDataUpdateGetDTO, List<FieldAttrEntity> explainList, PaasFormEntityExt form, PaasFormDataEntityExt paasFormDataEntityExt) throws XbbException {
        boolean formCopy = Objects.nonNull(formDataUpdateGetDTO.getSaasSpecialParamPojo()) && Objects.equals(formDataUpdateGetDTO.getSaasSpecialParamPojo().getFromCopy(), BasicConstant.ONE);
        handelSaasSpecialUpdate(explainList, form.getBusinessType(), paasFormDataEntityExt, formCopy, form.getDistributorMark());
        FormatExplainDTO formatExplainDTO = new FormatExplainDTO();
        BeanUtil.copyProperties(formDataUpdateGetDTO, formatExplainDTO);
        formatExplainDTO.setExplainList(explainList);
        formatExplainDTO.setDataEntity(paasFormDataEntityExt);
        formatExplainDTO.setResult(paasFormDataEntityExt.getData());
        formatExplainDTO.setFromCopy(formCopy);
        workReportHelp.formatAddExplain(formatExplainDTO);

        // 编辑时saas字段显示特殊逻辑
        workReportModel.formatUpdateExplain(formatExplainDTO);
    }

    @Override
    public void handelSaasSpecialUpdate(List<FieldAttrEntity> explainList, Integer businessType, PaasFormDataEntityExt formDataEntityExt, boolean formCopy, Integer distributorMark) throws XbbException {

    }



}
